package cn.aixuxi.security.uaa.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;

/**
 * 类描述
 *
 * @author ruozhuliufeng
 * @version 1.0
 * @date 2021/5/17 22:20
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 功能描述: 认证管理器
     * @author : ruozhuliufeng
     * @date : 2021/5/17 22:51
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 功能描述: 密码编码器
     * @author : ruozhuliufeng
     * @date : 2021/5/17 22:52
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(12);
    }

    /**
     * 功能描述: 安全拦截机制
     * @author : ruozhuliufeng
     * @date : 2021/5/17 22:53
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()// 关闭CSRF
                .authorizeRequests()
                .antMatchers("/test").hasAnyAuthority("test")// '/test'需要有'test'的权限
                .antMatchers("/login").permitAll()// /login不需要权限
                .antMatchers("/css/**","/js/**","/images/**","/fonts/**").permitAll()// 放行前端资源
                .anyRequest().authenticated()// 其余请求都需要权限
                .and()
                .formLogin()
                .loginPage("/login.ftl")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/index")
                .permitAll();// 表单登录
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
}
